﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using RemotingLibs.QuoteClass;
using TdxApiPool.Connect;
using TdxApiPool.Invoker;

namespace TdxApiPool.Looper
{
    public class HqLooper
    {
        private readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(HqLooper));
        private int _stop = 1;
        public TdxConnection TdxConnection;
        public List<Stkinfo> StockList { set; get; }
        public OnDisconnect Listener { set; get; }

        public HqLooper(TdxConnection tdxConnection, List<Stkinfo> stockList)
        {
            TdxConnection = tdxConnection;
            StockList = new List<Stkinfo>(stockList);
        }

        public void Start()
        {
            if (_stop == 0)
            {
                return;
            }
            _stop = 0;
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                try
                {
                    while (_stop == 0)
                    {
                        if (!StockList.Any())
                        {
                            Thread.Sleep(100);
                            continue;
                        }
                        var stkinfos = StockList;
                        var enumerator = Quote.Quotes(TdxConnection, stkinfos);
                        while (enumerator.MoveNext())
                        {
                            var quoteRtNs = enumerator.Current;
                            QueueLooper.GetInstance().AddData(quoteRtNs);
                        }
                        
                        if (TdxConnection.ConnectTime > 10)
                        {
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    _log.Error("通达信行情链接超时\t链接名称：" + TdxConnection.ConnectionName + "\t链接IP：" + TdxConnection.Ip);
                }
                finally
                {
                    Interlocked.Increment(ref _stop);
                    Listener?.Invoke(TdxConnection);
                }
            });
        }

        public void SetStkList(List<Stkinfo> list)
        {
            StockList = list;
        }

        public void Stop()
        {
            Interlocked.Increment(ref _stop);
        }

        public delegate void OnDisconnect(TdxConnection connection);
    }
}